import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import VueEcharts from 'vue-echarts';
import 'echarts';
import ElementPlus from 'element-plus';
import 'element-plus/dist/index.css';
import { createPinia } from 'pinia';
import zhCn from 'element-plus/es/locale/lang/zh-cn';

// 添加路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('jwtToken')
  
  // 处理未认证访问需要登录的页面
  if (to.meta.requiresAuth) {
    if (!token) {
      next({ name: 'login', query: { redirect: to.fullPath }})
      return
    }
    
    // 检查token是否过期
    const payload = JSON.parse(atob(token.split('.')[1]))
    if (Date.now() > payload.exp * 1000) {
      localStorage.removeItem('jwtToken')
      next('/login')
      return
    }
  }

  // 处理已登录用户访问guest页面
  if (to.meta.guest && token) {
    next(from.path || '/')
    return
  }

  // 处理404页面认证
  if (to.name === 'notFound' && !token) {
    next('/login')
    return
  }

  next()
})

const app = createApp(App);
app.component('v-chart', VueEcharts);
app.use(ElementPlus, {
  locale: zhCn, // 设置语言为中文
});
app.use(router);
app.use(createPinia());

app.mount('#app');
